#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2019/7/28
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

import os
import tkinter as tk
from tkinter.ttk import Combobox
from tkinter import filedialog


class FileRM(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.__file_dir_path = None
        self.__file_list = None
        self.__run_mode = None
        self.__begin_flag = None
        self.__result_flag = None
        self.__mode_list = "清除", "替换", "追加"
        self.__gui_init()

    def __esc_bind(self, event):
        self.quit()

    def __set_gui_display(self):
        self.title("File_Rename")
        gui_w = 200
        gui_h = 230
        x = (self.winfo_screenwidth() - gui_w) / 2
        y = (self.winfo_screenheight() - gui_h) / 2
        self.geometry("%dx%d+%d+%d" % (gui_w, gui_h, x, y))
        self.columnconfigure(0, weight=1)
        self.bind("<Escape>", self.__esc_bind)

    def __begin_cfg(self):
        self.__begin_frame = tk.Frame(self)
        self.__begin_title = tk.Label(self.__begin_frame, text="目标字符", justify="right", width=6)
        self.__begin_input = tk.Entry(self.__begin_frame, justify="center", width=14)
        for w in enumerate([self.__begin_title, self.__begin_input]):
            w[1].grid(row=0, column=w[0], padx=5)

    def __result_cfg(self):
        self.__result_frame = tk.Frame(self)
        self.__result_title = tk.Label(self.__result_frame, text="替换字符", justify="right", width=6)
        self.__result_input = tk.Entry(self.__result_frame, justify="center", width=14)
        for w in enumerate([self.__result_title, self.__result_input]):
            w[1].grid(row=0, column=w[0], padx=5)

    def __select_cfg(self):
        self.__select_frame = tk.Frame(self)
        self.__select_title = tk.Label(self.__select_frame, text="选择模式", justify="right", width=6)
        self.__select_mode = Combobox(self.__select_frame, justify="center", width=11, values=self.__mode_list)
        for w in enumerate([self.__select_title, self.__select_mode]):
            w[1].grid(row=0, column=w[0], padx=5)

    def __gui_init(self):
        self.__set_gui_display()
        self.__begin_cfg()
        self.__result_cfg()
        self.__select_cfg()
        self.__select_dir_button = tk.Button(self, text="选择文件夹", width=10, command=lambda: self.__select_file_dir())
        self.__run_button = tk.Button(self, text="开始", width=10, command=lambda: self.__start_button())
        gui_widgets = (self.__select_dir_button, self.__begin_frame, self.__result_frame, self.__select_frame,
                       self.__run_button)
        # default value
        self.__begin_input.insert(0, "[mqms2]")
        self.__select_mode.insert(0, self.__mode_list[0])

        for w in enumerate(gui_widgets):
            w[1].grid(row=w[0], column=0, pady=10)

    def __select_file_dir(self):
        self.__file_dir_path = filedialog.askdirectory()
        if self.__file_dir_path:
            try:
                os.chdir(self.__file_dir_path)
                self.__file_list = os.listdir(".")
            except OSError:
                self.__error_msg("path")

    def __common_value(self):
        if self.__file_dir_path:
            self.__begin_flag = str(self.__begin_input.get())
            self.__result_flag = str(self.__result_input.get())
            self.__run_mode = str(self.__select_mode.get())
        else:
            self.__error_msg("path")

    def __delete_flag(self):
        rm_list = [i.replace(self.__begin_flag, "") for i in self.__file_list]
        cacke_dict = dict(zip(self.__file_list, rm_list))
        for k, v in cacke_dict.items():
            os.rename(k, v)

    def __replace_flag(self):
        rm_list = [i.replace(self.__begin_flag, self.__result_flag) for i in self.__file_list]
        cacke_dict = dict(zip(self.__file_list, rm_list))
        for k, v in cacke_dict.items():
            os.rename(k, v)

    def __add_flag(self):
        def generate_new_name():
            name_list = [i.split(".")[0] for i in self.__file_list]
            ext_name = [i.split(".")[1] for i in self.__file_list]
            for i in enumerate(name_list):
                name_list[i[0]] = i[1] + self.__result_flag + "." + ext_name[i[0]]
            return name_list
        new_file_names = generate_new_name()
        cacke_dict = dict(zip(self.__file_list, new_file_names))
        for k, v in cacke_dict.items():
            os.rename(k, v)

    def __error_msg(self, e_type):
        from tkinter import messagebox

        if e_type == "mode":
            messagebox.showerror(self, message="模式错误！")
        elif e_type == "path":
            messagebox.showerror(self, message="请选择文件目录！")

    def __start_button(self):
        self.__common_value()
        if self.__run_mode:
            if self.__run_mode == "清除":
                self.__delete_flag()
            elif self.__run_mode == "替换":
                self.__replace_flag()
            elif self.__run_mode == "追加":
                self.__add_flag()
            else:
                self.__error_msg("mode")


if __name__ == '__main__':
    demo = FileRM()
    demo.mainloop()
